﻿using AForge.Video;
using AForge.Video.DirectShow;
using Newtonsoft.Json;
using pictureAnalyse;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;

namespace HongLingJin
{
    public partial class FormMain : Form
    {
        ConfigFile cf = new ConfigFile("HongLingJin");
        private AppSettingsReader settingsReader = new AppSettingsReader();
        private static FormMain instance = null;
        private FilterInfoCollection videoDevices;
        private VideoCaptureDevice videoDevice;
        private int selectedDeviceIndex = 0;
        private VisitorInfoDAL viDAL;
        private string timeType = "指定时间段";
        private Bitmap bitmap;
        private string password = null;
        private string username = null;
        HttpWebRequest httpWebRequest = null;
        HttpWebResponse httpWebResponse = null;
        private string token = null;
        Lazy<ReadIDCard> reader = new Lazy<ReadIDCard>();
        public FormMain()
        {
            InitializeComponent();
        }

        public static FormMain CreateInstance()
        {
            if (FormMain.instance == null || FormMain.instance.IsDisposed == true)
            {
                FormMain.instance = new FormMain();
            }

            return FormMain.instance;
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            this.username = (string)settingsReader.GetValue("username", typeof(string));
            this.password = (string)settingsReader.GetValue("password", typeof(string));
            Account account = new Account();
            account.username = this.username;
            account.password = md5(this.password);
            string data = JsonConvert.SerializeObject(account);
            string a = login(data);
            LoginResult lr = (LoginResult)JsonToObject(a, new LoginResult());
            token = lr.result;
            if (lr.message == "OK")
            {
                string c = visitorsTags();
                VisitorTags vt = FromJSON<VisitorTags>(c);
                cbTagIdList.DataSource = vt.result;
                cbTagIdList.DisplayMember = "tag_name";
                cbTagIdList.ValueMember = "tag_id";
                cbTagIdList.SelectedIndex = 0;
            }
            ArrayList al = new ArrayList();
            al.Add(new ComboxValue("其他", "0"));
            al.Add(new ComboxValue("商务洽谈", "1"));
            al.Add(new ComboxValue("面试", "2"));
            al.Add(new ComboxValue("亲友会见", "3"));
            al.Add(new ComboxValue("外卖快递", "4"));
            cbPurpose.DataSource = al;
            cbPurpose.DisplayMember = "DisplayText";
            cbPurpose.ValueMember = "RealValue";
            cbPurpose.SelectedIndex = 0;
            
     
            this.tbStartTime.Enabled = true;
            this.tbEndTime.Enabled = true;
            this.btnSubmit.Enabled = false;
            this.tbCreateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string start = DateTime.Now.ToString("yyyy-MM-dd")+" 00:00:00";
            string end = DateTime.Now.ToString("yyyy-MM-dd")+" 23:59:59";
            DateTimeChoser.AddTo(tbStartTime, Convert.ToDateTime(start));
            DateTimeChoser.AddTo(tbEndTime, Convert.ToDateTime(end)); 
            try
            {
                this.videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                if (this.videoDevices.Count != 0)
                {
                    foreach (FilterInfo info in this.videoDevices)
                    {
                        this.cboCameras.Items.Add(info.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCapture_Click(object sender, EventArgs e)
        {
             this.tbCreateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
             if (videoDevice == null)
                 return;
             bitmap = video.GetCurrentVideoFrame();
             this.picImage.Image = bitmap;
             this.btnSubmit.Enabled = true;
        }

        private void cboCameras_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.videoDevice = new VideoCaptureDevice(this.videoDevices[this.cboCameras.SelectedIndex].MonikerString);
            if (this.videoDevice != null)
            {
                this.videoDevice.NewFrame += VideoDevice_NewFrame;
            }
        }

        private void VideoDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();

            this.picImage.Image = bitmap;
        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {

            this.video.WaitForStop();
        }

        private void btnCamera_Click(object sender, EventArgs e)
        {
            if (this.btnCamera.Text == "开摄像头")
            {
                this.videoDevice = new VideoCaptureDevice(this.videoDevices[0].MonikerString);
                this.video.VideoSource = videoDevice;
                this.video.Start();
                this.btnCamera.Text = "关摄像头";
            }
            else
            {
                this.btnCamera.Text = "开摄像头";
                    this.video.WaitForStop();
            }
            
        }

        private string login(string data)
        {
            string url = (string)settingsReader.GetValue("login", typeof(string));
            httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json;charset=utf-8";
            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 20000;
            byte[] btBodys = Encoding.UTF8.GetBytes(data);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
            httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();
            httpWebResponse.Close();
            streamReader.Close();
            //httpWebRequest.Abort();
            
            return responseContent;
        }

        private string addVisitors(string data,string token)
        {
            string url = (string)settingsReader.GetValue("addVisitors", typeof(string));
            httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json;charset=utf-8";
            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 20000;
            httpWebRequest.Headers.Add("Authorization", token);
            byte[] btBodys = Encoding.UTF8.GetBytes(data);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();

            httpWebResponse.Close();
            streamReader.Close();
            httpWebRequest.Abort();

            return responseContent;

        }

        private string visitorsTags()
        {
            string url = (string)settingsReader.GetValue("visitorsTags", typeof(string));
            httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json;charset=utf-8";
            httpWebRequest.Method = "GET";
            httpWebRequest.Timeout = 20000;
            httpWebRequest.Headers.Add("Authorization", token);

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();

            httpWebResponse.Close();
            streamReader.Close();

            return responseContent;
        }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (this.tbName.Text == String.Empty)
            {
                MessageBox.Show("请填写访客姓名");
            }

            if (this.tbVisiteeName.Text == String.Empty)
            {
                MessageBox.Show("请填写被访者姓名");
            }
            if (this.tbVisiteeName.Text == String.Empty || this.tbName.Text == String.Empty)
            {
                return;
            }
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                string fileName = @"D:\image\" + DateTime.Now.ToString("yyyyMMddHHmmssff") + ".jpg";
                bitmap.Save(fileName, ImageFormat.Jpeg);
                Visitor visitor = new Visitor();
                VisitorInfo visitorInfo = new VisitorInfo();
                visitorInfo.Id = System.Guid.NewGuid().ToString();
                visitorInfo.Name = this.tbName.Text;
                visitorInfo.Visitee_name = this.tbVisiteeName.Text;
                visitorInfo.Company = this.tbCompany.Text;
                visitorInfo.Visit_purpose = this.cbPurpose.SelectedValue.ToString();
                visitorInfo.Phone = this.tbPhone.Text;
                visitorInfo.Identity_number = this.tbIDCard.Text;
                visitorInfo.createDate = (int)(Convert.ToDateTime(this.tbCreateTime.Text) - startTime).TotalSeconds;
                visitorInfo.File = fileName;
                visitorInfo.Card_no = "";
                if (this.timeType == "长期")
                {
                    visitorInfo.Visit_time_type = "0";
                }
                else
                {
                    visitorInfo.Visit_time_type = "1";
                    visitorInfo.Visit_start_timestamp = (int)(Convert.ToDateTime(this.tbStartTime.Text) - startTime).TotalSeconds;
                    visitorInfo.Visit_end_timestamp = (int)(Convert.ToDateTime(this.tbEndTime.Text) - startTime).TotalSeconds;
                }

                visitor.Tag_id_list = this.cbTagIdList.SelectedValue.ToString();
                this.viDAL = new VisitorInfoDAL();
                if (viDAL.Insert(visitorInfo) > 0)
                {
                    VisitorDAL vDAL = new VisitorDAL();
                    visitor.Image_file = fileName;
                    visitor.Id = System.Guid.NewGuid().ToString();
                    visitor.VistorInfoId = visitorInfo.Id;
                    if (vDAL.Insert(visitor) > 0)
                    {
                        VisitorInfoJson viJson = new VisitorInfoJson();
                        VisitorJson vJson = new VisitorJson();
                        viJson.company = visitorInfo.Company;
                        viJson.name = visitorInfo.Name;
                        viJson.phone = visitorInfo.Phone;
                        viJson.visit_end_timestamp = visitorInfo.Visit_end_timestamp;
                        viJson.visit_purpose = visitorInfo.Visit_purpose;
                        viJson.visit_start_timestamp = visitorInfo.Visit_start_timestamp;
                        viJson.visit_time_type = visitorInfo.Visit_time_type;
                        viJson.visitee_name = visitorInfo.Visitee_name;
                        viJson.identity_number = visitorInfo.Identity_number;
                        viJson.card_no = visitorInfo.Card_no;
                        vJson.face_image_content = ImageToBase64();
                        bitmap.Dispose();


                        vJson.person_information = viJson;
                        vJson.tag_id_list = new List<string>();
                        vJson.tag_id_list = new List<string>(visitor.Tag_id_list.Split(','));
                        string data1 = JsonConvert.SerializeObject(vJson);
                        data1 = "{\"visitor_list\":[" + data1 + "]}";
                        string b = addVisitors(data1,token);
                        //RetrunResult rr = (RetrunResult)JsonToObject(b, new RetrunResult());
                        //MessageBox.Show(rr.message);
                        MessageBox.Show(b);
                    }
                }
            
        }

        public VisitorTags FromJSON<VisitorTags>(string input)
        {
            try{
                return JsonConvert.DeserializeObject<VisitorTags>(input);
            }
            catch (Exception ex)
            {
                return default(VisitorTags);
            }
        }
        private void rbtnLong_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnLong.Checked)
            {
                this.timeType = this.rbtnLong.Text;
                this.tbStartTime.Enabled = false;
                this.tbEndTime.Enabled = false;
            }
        }

        private void rbtnShort_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnShort.Checked)
            {
                this.timeType = this.rbtnShort.Text;
                this.tbStartTime.Enabled = true;
                this.tbEndTime.Enabled = true;
            }
        }

        private string ImageToBase64()
        {
            try
            {
                MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] bytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(bytes, 0, (int)stream.Length);
                stream.Close();
                return Convert.ToBase64String(bytes);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private string md5(string password)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] hashedDataBytes;
            hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(password));
            StringBuilder tmp = new StringBuilder();
            foreach (byte i in hashedDataBytes)
            {
                tmp.Append(i.ToString("x2"));
            }
            return tmp.ToString();//默认情况
            
        }

       
        private class LoginResult{

            public string result { get; set; }

            public string rtn { get; set; }

            public string message { get; set; }
        }

        public static object JsonToObject(string jsonString, object obj)
        {
            return JsonConvert.DeserializeObject(jsonString, obj.GetType());
        }

        private void btnReadIdentityCard_Click(object sender, EventArgs e)
        {
            this.tbCreateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            reader.Value.IDCardInfoCompleted += (args) =>
            {
                this.tbName.Text = args.Name;
                this.picImage.Image= ReadImageFile(args.Photo);
                this.tbIDCard.Text = args.Code;
            };

            Action delegateReader = () => reader.Value.ReadCard();
            delegateReader.BeginInvoke(null, null);
        }

        public Bitmap ReadImageFile(string path)
        {
            MessageBox.Show(path);
            FileStream fs = File.OpenRead(path); //OpenRead
            int filelength = 0;
            filelength = (int)fs.Length; //获得文件长度 
            Byte[] image = new Byte[filelength]; //建立一个字节数组 
            fs.Read(image, 0, filelength); //按字节流读取 
            Image result = Image.FromStream(fs);
            fs.Close();
            bitmap = new Bitmap(result);
            return bitmap;
        }

        private void btnVisitorHistory_Click(object sender, EventArgs e)
        {
            IntradayFrom info = new IntradayFrom();
            info.ShowDialog();
        }

    }
}
